import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, message, InputNumber } from 'antd';
import type { Student } from '../../../service/student';
import { getClassList } from '../../../service/index';
import { DefaultOptionType } from 'antd/es/select';

const GENDER_OPTIONS = [
  { value: '男', label: '男' },
  { value: '女', label: '女' },
];

interface StudentModalProps {
  open: boolean;
  onCancel: () => void;
  onOk: (values: any) => void;
  editingStudent?: Student;
  title?: string;
}

const StudentModal: React.FC<StudentModalProps> = ({
  open,
  onCancel,
  onOk,
  editingStudent,
  title = '添加学生'
}) => {
  const [form] = Form.useForm();
  const [classList, setClassList] = useState<DefaultOptionType[]>([]);

  useEffect(() => {
    const fetchClassList = async () => {
      try {
        const res = await getClassList({ 
          page: 1, 
          pagesize: 100,
          name: '',
          classify: '',
          teacher: '',
          status: 1
        });
        console.log('Class list response:', res);
        
        if (res.data && res.data.code === 0) {
          const classes = res.data.data.list.map((item: any) => ({
            label: item.name,
            value: item._id,
            key: item._id,
            classify: item.classify?.name,
            teacher: item.teacher?.username
          }));
          console.log('Processed classes:', classes);
          setClassList(classes);
        } else {
          console.error('Failed to fetch class list:', res);
          message.error(res.data?.msg || '获取班级列表失败');
        }
      } catch (error) {
        console.error('获取班级列表失败', error);
      }
    };

    if (open) {
      fetchClassList();
    }

    if (open && editingStudent) {
      form.setFieldsValue({
        username: editingStudent.username,
        name: editingStudent.className || editingStudent.username,
        className: editingStudent.classId,
        sex: editingStudent.sex || undefined,
        idCard: editingStudent.idCard || '',
        email: editingStudent.email || '',
        age: editingStudent.age || null,
        status: editingStudent.status ?? 1
      });
    } else {
      form.resetFields();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, editingStudent]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      onOk(values);
    } catch (error) {
      console.error('Validate Failed:', error);
    }
  };

  return (
    <Modal
      title={title}
      open={open}
      onOk={handleOk}
      onCancel={onCancel}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{ 
          status: 1,
          sex: '',
          email: '',
          idCard: '',
          description: '',
          age: null
        }}
      >
        <Form.Item
          name="username"
          label="用户名"
          rules={[
            { required: true, message: '请输入用户名' },
            { min: 0, max: 20, message: '用户名长度为4-20位字符' }
          ]}
        >
          <Input placeholder="请输入用户名" />
        </Form.Item>

        <Form.Item
          name="password"
          label="密码"
          rules={[
            { required: !editingStudent, message: '请输入密码' },
            { min: 6, max: 20, message: '密码长度为6-20位字符' }
          ]}
        >
          <Input.Password placeholder="请输入密码" />
        </Form.Item>

        <Form.Item
          name="name"
          label="姓名"
          rules={[
            { required: true, message: '请输入姓名' },
            { min: 2, max: 20, message: '姓名长度为2-20位字符' }
          ]}
        >
          <Input placeholder="请输入姓名" />
        </Form.Item>

        <Form.Item
          name="sex"
          label="性别"
          rules={[{ required: false }]}
        >
          <Select
            placeholder="请选择性别（可选）"
            options={[...GENDER_OPTIONS, { value: '', label: '未选择' }]}
            allowClear
          />
        </Form.Item>

        <Form.Item
          name="age"
          label="年龄"
          rules={[
            { required: false },
            {
              validator: (_, value) => {
                if (value === undefined || value === null || value === '') {
                  return Promise.resolve();
                }
                const numValue = Number(value);
                if (isNaN(numValue) || numValue < 0 || numValue > 120) {
                  return Promise.reject(new Error('请输入0-120之间的年龄'));
                }
                return Promise.resolve();
              }
            }
          ]}
        >
          <InputNumber 
            style={{ width: '100%' }} 
            min={0} 
            max={120} 
            placeholder="请输入年龄（可选）" 
          />
        </Form.Item>

        <Form.Item
          name="className"
          label="班级"
          rules={[{ required: true, message: '请选择班级' }]}
        >
          <Select 
            placeholder="请选择班级"
            options={classList}
            loading={classList.length === 0}
          />
        </Form.Item>

        <Form.Item
          name="idCard"
          label="身份证号"
          rules={[
            { 
              message: '请输入正确的身份证号' 
            }
          ]}
        >
          <Input placeholder="请输入身份证号（可选）" />
        </Form.Item>

        <Form.Item
          name="email"
          label="邮箱"
          rules={[
            { 
              type: 'email', 
              message: '请输入正确的邮箱格式' 
            }
          ]}
        >
          <Input placeholder="请输入邮箱（可选）" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default StudentModal;